<template>
  <a-spin :spinning="loading" size="large">
    <van-form @submit="onSubmit" @failed="onFailed" ref="formRef">
      <h3>1.报修类型:</h3>
      <van-cell-group inset>
        <van-field v-model="checkTypeName" is-link readonly label="报修类型" placeholder="请选择"
          @click="!isUpdate ? show = true : ''" />
      </van-cell-group>
      <h3>2.报修科室:</h3>
      <van-cell-group inset>
        <van-field v-model="checkPlaceName" is-link readonly label="报修科室" placeholder="请选择"
          @click="!isUpdate ? mini = true : ''" />
      </van-cell-group>
      <h3>3.科室地点描述:</h3>
      <van-cell-group inset>
        <van-field v-model="messagePlace" type="textarea" rows="3" autosize placeholder="详情描述"
          :disabled="isUpdate"></van-field>
      </van-cell-group>
      <h3>4.报修详情描述:</h3>
      <van-cell-group inset>
        <van-field v-model="message" type="textarea" rows="3" autosize placeholder="详情描述"
          :disabled="isUpdate"></van-field>
      </van-cell-group>
      <h3>5.报修照片:</h3>
      <van-cell-group inset>
        <van-uploader v-if="!isUpdate" multiple v-model="fileList" :after-read="afterRead" :before-read="beforeRead"
          :preview-options='{closeable:true}' :disabled="isUpdate"></van-uploader>
        <a-image :width="150" v-else v-for="item in fileList" :src=" 'data:image/jpg;base64,' + item"></a-image>
      </van-cell-group>
      <br>
      <div class="btn">
        <van-button v-if="!isUpdate" type="primary" @click="doSubmit">提交</van-button>
      </div>
    </van-form>

    <!-- 科室列表 -->
    <van-popup v-model:show="mini" position="bottom">
      <van-picker title="选择科室" :columns="gridList" @confirm="confirmGrid" @cancel="mini = false"
        :columns-field-names="{text:'placeName', value: 'id'}"></van-picker>
    </van-popup>

    <!-- 类型列表 -->
    <van-popup v-model:show="show" position="bottom">
      <van-picker title="选择类型" :columns="typeList" @confirm="confirmType" @cancel="show = false"
        :columns-field-names="{text:'typeName', value: 'id'}"></van-picker>
    </van-popup>
  </a-spin>
</template>

<script setup>
  import { ref, onMounted, inject } from "vue"
  import { Field as VanField, Form as VanForm, RadioGroup as VanRadioGroup, CellGroup as VanCellGroup, Uploader as VanUploader, Button as VanButton, Popup as VanPopup, Picker as VanPicker } from "vant";
  import { useRoute } from "vue-router";
  import router from "@/route/index.js";
  import { photoUploadBase64, getWxPlace, submitData, getWxType } from "@/api/common.js";
  import moment from "moment"
  import * as imageConversion from 'image-conversion'

  const mini = ref(false);
  const checkPlace = ref("");
  const checkType = ref("");
  const checkPlaceName = ref("");
  const checkTypeName = ref("");
  const loading = ref(false),
    show = ref(false),
    toast = inject("toast"),
    route = useRoute(),
    message = ref(""),
    messagePlace = ref(""),
    fileList = ref([]),
    formRef = ref(null),
    recordId = ref(""),
    isUpdate = ref(false); //修改和详情
  const imgBaseUrl = ref("");
  const gridList = ref([]);
  const typeList = ref([]);
  const userInfo = ref(JSON.parse(localStorage.getItem("SAVE_USER_INFO")));

  onMounted(() => {
    getWxPlace().then(res => {
      gridList.value = res
    })
    getWxType().then(res => {
      typeList.value = res
    })
  })

  function confirmGrid(val) {
    mini.value = false
    checkPlaceName.value = val.placeName
    checkPlace.value = val.id
  }

  function confirmType(val) {
    show.value = false
    checkTypeName.value = val.typeName
    checkType.value = val.id
    gridList.value.forEach(item => {
      if(item.placeName == val.placeName) {
        checkPlace.value = item.id
        checkPlaceName.value = item.placeName
      }
    })
  }

  function onFailed(error) {
    console.log(error)
  }

  function doSubmit() {
    formRef.value.submit();
  }

  function onSubmit() {
    if (!fileList.value.length && !message.value.trim()) {
      toast.msg("报修详情描述和报修图片必填其中一个！");
      return
    }
    if (!messagePlace.value.trim()) {
      toast.msg("请填写科室地点详情描述！")
      return
    }
    if (!checkTypeName.value) {
      toast.msg("请选择报修类型！")
      return
    }
    if (!checkPlaceName.value) {
      toast.msg("请选择报修科室！")
      return
    }
    let imgList = []
    fileList.value.forEach(item => {
      imgList.push(item.msg)
    })
    let obj = {
      bxTypeId: checkType.value,
      bxTypeName: checkTypeName.value,
      checkPlace: messagePlace.value.trim(),
      checkContent: message.value.trim(),
      placeId: checkPlace.value,
      checkPlaceName: checkPlaceName.value,
      imgArrayAbnormal: imgList,
      userId: userInfo.value.userId,
      checkUserName: userInfo.value.realName
    }
    loading.value = true
    submitData(obj).then(res => {
      if (res.code == 200) {
        toast.success('提交成功！');
        setTimeout(() => {
          loading.value = false;
          router.go(-1);
        }, 1000)
      } else {
        loading.value = false
        toast.msg(res.message)
      }
    }, err => {
      loading.value = false
      toast.msg(err)
    })
  }

  function beforeRead(file) {
    if (Array.isArray(file)) {
      return Promise.all(file.map(f => {
        return imageConversion.compressAccurately(f, 200).then(res => {
          return new File([res], f.name, { type: res.type, lastModified: Date.now() });
        });
      }));
    } else {
      return new Promise((resolve, reject) => {
        imageConversion.compressAccurately(file, 200).then(res => {
          res = new File([res], file.name, { type: res.type, lastModified: Date.now() })
          resolve(res)
        })
      });
    }
  }

  function afterRead(file) {
    uploadFile(file);
  }
  function uploadFile(file) {
    file.status = "uploading";
    loading.value = true;
    if(Array.isArray(file)) {
      file.forEach(item => {
        apiUpLoadImg(item);
      })
    } else {
      apiUpLoadImg(file);
    }
  }

  function getBase64(file) {
    return new Promise(function (resolve, reject) {
      const reader = new FileReader();
      let imgResult = "";
      reader.readAsDataURL(file);
      reader.onload = function () {
        imgResult = reader.result;
      };
      reader.onerror = function (error) {
        reject(error);
      };
      reader.onloadend = function () {
        resolve(imgResult);
      };
    });
  }

  function apiUpLoadImg(file) {
    getBase64(file.file).then(res => {
      let obj = {
        base64: res
      }
      //接口需要传的参数
      photoUploadBase64(obj).then(res => {
        if (res.code == 200) {
          file.status = "success";
          file.msg = res.message;
        }
        loading.value = false;
      }, err => {
        loading.value = false
        // alert(err)
      })
    })
  }

</script>

<style lang="less" scoped>
  h3 {
    font-weight: 700;
    margin: 5px 15px;
  }

  :deep(.van-field__label) {
    width: calc(100% - 150px);
  }

  .special :deep(.van-field__label) {
    width: calc(100% - 200px);
  }

  :deep(.van-uploader) {
    margin: 8px 0 0 10px;
  }

  .btn {
    margin: 0 16px;

    button {
      width: 100%;
      margin-bottom: 10px;
    }

  }

  :deep(.van-uploader__preview) {
    margin-right: 5px;
  }

  .home-title {

    margin-left: 15px;
    margin-top: 20px;

    h1 {
      font-weight: 700;
      margin: 0;
    }

    h3 {
      font-weight: 700;
      margin: 0;
      margin-left: 10px;
    }

    span {
      display: block;
      margin-left: 15px;
      margin-bottom: 3px;

      font.yellow {
        border: 1px solid greenyellow;
        color: greenyellow;
        padding: 1px 3px;
      }

      font.yellow {
        border: 1px solid #ffea00;
        color: #ffea00;
        padding: 1px 3px;
      }

      font.orange {
        border: 1px solid orange;
        color: orange;
        padding: 1px 3px;
      }

      font.red {
        border: 1px solid red;
        color: red;
        padding: 1px 3px;
      }

    }

  }

  :deep(.van-popup--bottom) {
    background-color: rgb(246, 247, 248);
  }
</style>